package com.ruoyi.project.common

import com.google.code.kaptcha.Producer
import com.ruoyi.common.constant.*
import com.ruoyi.common.utils.sign.Base64
import com.ruoyi.common.utils.uuid.IdUtils
import com.ruoyi.framework.redis.RedisCache
import com.ruoyi.framework.web.domain.AjaxResult
import com.ruoyi.project.system.service.ISysConfigService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.util.FastByteArrayOutputStream
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import java.awt.image.BufferedImage
import java.io.IOException
import java.util.concurrent.*
import javax.annotation.Resource
import javax.imageio.ImageIO
import javax.servlet.http.HttpServletResponse

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
open class CaptchaController {
    @Resource(name = "captchaProducer")
    private val captchaProducer: Producer? = null

    @Resource(name = "captchaProducerMath")
    private val captchaProducerMath: Producer? = null

    @Autowired
    private val redisCache: RedisCache? = null

    // 验证码类型
    @Value("\${ruoyi.captchaType}")
    private val captchaType: String? = null

    @Autowired
    private val configService: ISysConfigService? = null

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @Throws(IOException::class)
    fun getCode(response: HttpServletResponse?): AjaxResult {
        val ajax: AjaxResult = AjaxResult.success()
        val captchaEnabled = configService!!.selectCaptchaEnabled()
        ajax["captchaEnabled"] = captchaEnabled
        if (!captchaEnabled) {
            return ajax
        }

        // 保存验证码信息
        val uuid = IdUtils.simpleUUID()
        val verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid
        var capStr: String? = null
        var code: String? = null
        var image: BufferedImage? = null

        // 生成验证码
        if ("math" == captchaType) {
            val capText = captchaProducerMath!!.createText()
            capStr = capText.substring(0, capText.lastIndexOf("@"))
            code = capText.substring(capText.lastIndexOf("@") + 1)
            image = captchaProducerMath.createImage(capStr)
        } else if ("char" == captchaType) {
            code = captchaProducer!!.createText()
            capStr = code
            image = captchaProducer.createImage(capStr)
        }
        redisCache!!.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES)
        // 转换流信息写出
        val os = FastByteArrayOutputStream()
        try {
            ImageIO.write(image, "jpg", os)
        } catch (e: IOException) {
            return AjaxResult.error(e.message)
        }
        ajax["uuid"] = uuid
        ajax["img"] = Base64.encode(os.toByteArray())
        return ajax
    }
}
